var param = JSON.parse(localStorage.getItem('param'));
var productId = param.productId;
var type = param.type;
var params;
$(function(){
	init();
	initButton();
});
//初始化页面
function init(){
	//从后台请求商品和用户的信息
	$.ajax({
		type : "get",
		url : server_url
				+ 'rest/tea/order/getOrderInfoBefore.do?ran=' + Math.random(),
		dataType : 'json',
		async : true,
		data : {
			token : token,
			productId:productId,
			userId:localStorage.getItem('userid')
		},
		success : function(result) {
			console.log(result);
			if (result.retCode == '0000') {
				var product = result.data.teaProduct;
				var tPrice ;
				if(product.cateid==3||product.cateid==4){//parseFloat($('#productNum').html());
					tPrice = product.priceretailguide;
				}else{
					tPrice = product.priceretailguide;
				}
				
				var addr = result.data.teaUserAddr;
				var addrStr = "";
				if(addr){
					addrStr = '<div class="now-address" addrid="'+addr.id+'"><p class="name">收件人：'+addr.userName+'<span>'+addr.userPhone+'</span></p><p class="now-con">'+addr.userArea+' '+addr.userAddr+'</p></div>';
				}else{
					addrStr = '<div class="now-address"><p class="name">请添加收货地址<span></span></p><p class="now-con"></p></div>';
				}
				var proStr = '<div class="shop-box"><span>德盛茶叶行</span></div><div class="pro-box"><div class="pro-list clear"><img src="'+product.pic+'" alt="" class="fl"><div class="skill-box fr"><p class="skill-name">'+product.productname+'</p><p class="num" >¥<span id="productNum">'+tPrice+'</span></p></div></div></div>';
				$('.product-info').html(proStr);
				$('.address-info').html(addrStr);
				$('#freight').html(product.freight);
				$('#orderPrice').html(parseFloat(tPrice)+parseFloat(product.freight));
				if(param.addrId){
					addrId = param.addrId;
					$.ajax({
						type : "get",
						url : server_url
								+ 'rest/tea/user/addr/getAddrInfo.do?ran=' + Math.random(),
						dataType : 'json',
						async : true,
						data : {
							token : token,
							addrId:addrId
						},
						success : function(result) {
							if (result.retCode == '0000') {
								var addr = result.data;
								var addrStr = '<div class="now-address" addrid="'+addr.id+'"><p class="name">收件人：'+addr.userName+'<span>'+addr.userPhone+'</span></p><p class="now-con">'+addr.userArea+' '+addr.userAddr+'</p></div>';
								$('.address-info').html(addrStr);	
							} 
						}
					});
				}
			} 
		}
	});
	
}
//初始化绑定事件
function initButton(){
	//提交订单
	$('.buy-btn').on('click',function(){
		if(!checkOrder()){
			return;
		}
		console.log(params);
		//提交订单的时候先向后台发送请求，请求验证通过之后，生成订单，生成的订单号返回到前台，然后再跳转到订单页面，如果失败，要想前台返回失败原因
		$.ajax({
			type : "post",
			url : server_url
					+ 'rest/tea/order/saveOrder.do?ran=' + Math.random(),
			dataType : 'json',
			async : true,
			contentType:"application/json", 
			data : params,
			success : function(result) {
				console.log(result);
				if (result.retCode == '0000') {
					param.orderId = result.data.id;
					localStorage.setItem('param',JSON.stringify(param));
					window.location = server_url + "order.do";
				} 
			}
		});
		
		
		
		//window.location = server_url + "order.do";
	});
	//更换地址
	$('body').on('click','.now-address',function(){
		localStorage.setItem('param',JSON.stringify(param));
		window.location = server_url + "addressList.do";
	});
	//增加数量
	$('.add').on('click',function(){
		var num = parseInt($('.con').html())+1;
		$('.con').html(num);
		var price = parseFloat($('#productNum').html());
		$('#orderPrice').html(price*num+parseFloat($('#freight').html()));
		
	});
	//减少数量
	$('.reduce').on('click',function(){
		if(parseInt($('.con').html())<=1){
			return ;
		}else{
			var num = parseInt($('.con').html())-1;
			$('.con').html(num);
			var price = parseFloat($('#productNum').html());
			$('#orderPrice').html(price*num+parseFloat($('#freight').html()));
		}
	});
}
//检查订单
function checkOrder(){
	var productId = param.productId;//商品id
	var addrId = $('.now-address').attr('addrid'); //收货地址
	var num = parseInt($('.con').html()); //购买数量
	var freight = parseFloat($('#freight').html()); //运费
	var price = parseFloat($('#productNum').html()); //单价
	var orderPrice = parseFloat($("#orderPrice").html());
	var userId = localStorage.getItem('userid');
	if(!(orderPrice ==(num*price)+freight)){
		//如果总价不等于运费+数量*单价，提示用户刷新页面
		alert("计算错误，请重新刷新页面");
		return false;
	}
	if(!productId||""==productId){
		alert("请重新选择商品");
		return false;
	}
	if(!userId||""==userId){
		alert("请先登录");
		return false;
	}
	if(!addrId||""==addrId){
		alert("请重新选择收货地址");
		return false;
	}
	var order = {};
	order.productid = productId;
	order.addrid = addrId;
	order.conut = num;
	order.freight = freight;
	order.perunit = price;
	order.totalunit = orderPrice;
	order.userid = userId;
	order.type = type;
	params = JSON.stringify(order);
	return true;
	
}